<?php

namespace App\Http\Controllers\applet_api;

use App\Http\Controllers\Controller;
use App\Models\AppCartItem;
use Illuminate\Http\Request;

class CartItemController extends Controller
{

    public function index(Request $Request)
    {
        $limit = $Request->limit ?: 10;
        $page = $Request->page ?: 1;
        $page = $page * $limit - $limit;
        $sql = AppCartItem::where('user_id',$Request->uid)->with('sku')->with('SkuProduct');
        $total = $sql->count();
        $data = $sql->skip($page)->take($limit)->orderBy('id','asc')->get();
        return response()->json(['code' => '200', 'msg' => 'success','data'=>$data,'total'=>$total]);
    }

    public function info(Request $Request)
    {
        $data = AppCartItem::with('sku')->where('id',$Request->id)->first();
        return response()->json(['code' => '200', 'msg' => 'success','data'=>$data]);
    }

    public function store(Request $Request)
    {
        if(!$Request->product_sku_id){
            return response()->json(['code' => '403', 'msg' => '请选择产品']);
        }
        $data = AppCartItem::where('product_sku_id',$Request->product_sku_id)->first();
        if(!$data){
            $data = new AppCartItem();
            $data->user_id = $Request->uid;
            $data->product_sku_id = $Request->product_sku_id;
            $data->type = $Request->type ?? 0;
            $data->create_time = time();
        }
        
        if($data){
            $data->amount = $data->amount + 1;
        }else{
            $data->amount = $Request->amount ?? 1;
        }
        $data->update_time = time();
        $data->save();
        return response()->json(['code' => '200', 'msg' => 'success','data'=>$data]);
    }

    public function update(Request $Request)
    {
        if(!$Request->id){
            return response()->json(['code' => '403', 'msg' => '请选择要操作的记录']);
        }
        $data = AppCartItem::find($Request->id);
        $data->amount = $Request->amount ?? 1;
        $data->update_time = time();
        $data->save();
        return response()->json(['code' => '200', 'msg' => 'success','data'=>$data]);
    }

    public function delete(Request $Request)
    {
        if(!$Request->id){
            return response()->json(['code' => '403', 'msg' => '请选择要删除的记录']);
        }
        $data = AppCartItem::find($Request->id);
        if(!$data){
            return response()->json(['code' => '403', 'msg' => '记录不存在']);
        }
        if($data->user_id != $Request->uid){
            return response()->json(['code' => '403', 'msg' => '权限错误']);
        }
        $data->delete();
        return response()->json(['code' => '200', 'msg' => 'success']);
    }

    public function deleteAll(Request $Request)
    {
        AppCartItem::where('user_id',$Request->uid)->delete();
        return response()->json(['code' => '200', 'msg' => 'success']);
    }
}
